// 页面: 工作台-审批管理-申请
const $app = getApp()
Page({
  data: {
    Auth: {}, // 权限数据(勿删)
    userInfo: $app.userInfo || {}, // 用户信息
    // ===== 参数 =====
    param: {},
    fileKeys: ['filepath', 'filename'],
    error: null, // 错误验证
    // ===== 列表数据 =====
    listData: {
      depart: $app.listData.depart || [], // 部门
      assetsNum: [], // 资产编号
      assetsType: $app.listData.assetsType, // 资产类型
      useCondition: $app.listData.useSituation, // 使用情况
      includeMoney: $app.listData.includeMoney, // 涉及金额
      manageType: [], // 管理方式 ($app.listData.manageType)
      approveProcess: [] // 审批流程($app.listData.approveProcess)
    },
    // ===== 审批流程 =====
    approveProcess_person: { // 审批流程具体人员
      initiate: [],
      manageDepart: [],
      assetsManageDepart: [],
      departManager: [],
      groupLead: []
    },
    approveProcess_warning: null, // 警告提示
    // ===== 判断 =====
    judgeAuthName: '', // 当前使用的权限对应web页名称(用于判断提交按钮权限)
    judge_isAssetsAgree: {} // '经资产管理部审批'是否可用
    // ===== end =====
  },
  model (e) { $app.$common_wx.model(e, this) }, // 双向绑定
  // ========== 生命周期: 页面加载 ==========
  onLoad: function (options) {
    this.setData({
      userInfo: $app.userInfo,
      ['listData.depart']: $app.listData.depart
    })
    // ========== 获取列表数据: 部门 ==========
    if (!$app.listData.depart.length) {
      $app.$common_base.getListData_depart((data) => {
        this.setData({ ['listData.depart']: data })
      })
    }
    // ========== 获取权限数据(勿删) ==========
    const pages = getCurrentPages()
    const path = pages.length ? pages[pages.length - 1].route : null
    $app.$common_base.getAuth(path).then((Auth) => {
      console.log(Auth, 'Auth')
      this.setData({ Auth })
      this.judgeAuthEvent() // 判断权限
    })
    // ========== 获取权限数据(勿删) end ==========
  },
  // ========== 生命周期: 页面初次渲染完成 ==========
  onReady: function () {},
  // ========== 生命周期: 页面显示 ==========
  onShow: function () {},
  // ========== 生命周期: 页面隐藏 ==========
  onHide: function () {},
  // ========== 生命周期: 页面卸载 ==========
  onUnload: function () {},
  // ========== 判断权限 ==========
  judgeAuthEvent () {
    const Auth = this.data.Auth
    // 获取列表数据: 管理方式, 并判断是否有新增权限
    let manageType = []
    $app.listData.manageType.forEach(b => {
      const add = Auth[`${b.Auth}_add`] // 新增
      if (add) manageType.push(b)
    })
    if (!manageType.length) return
    this.setData({ ['listData.manageType']: manageType })
    this.init() // 初始化
  },
  // ========== 初始化 ==========
  init () {
    const manageType = this.data.listData.manageType
    const param = {
      // agreeNum: null, // 审批单号
      isAgree: '0', // 是否审批
      launchDepart: $app.userInfo.departid, // 发起部门id
      launchDepartName: $app.userInfo.departname, // 发起部门name
      writeTime: $app.$common.dateFormat(new Date(), 'YYYY-MM-DD'), // 发起日期
      assetsNum: null, // 资产编号
      manageCompany: null, // 管理部门id
      manageCompanyName: null, // 管理部门name
      assetsType: null, // 资产类型
      locatePlace: null, // 资产地址
      useCondition: null, // 使用情况
      includeMoney: null, // 涉及金额
      person: null, // 经办人
      manageType: manageType.length === 1 ? manageType[0].id : null, // 管理方式
      assetsStatus: null, // 资产会办情况
      filepath: null, // 附件路径
      filepathArr: [], // 附件路径Arr
      filename: null, // 附件路径
      filenameArr: [], // 附件路径Arr
      isAssetsAgree: 0, // 经资产管理部审批(0: 不经过, 1: 经过)
      agreeType: 0, // 审核状态(0: 保存草稿, 1: 提交)
      userid: $app.userInfo.id,
      name: $app.userInfo.name,
      launchUserId: $app.userInfo.id // 保存数据
    }
    this.setData({ param })
    this.launchDepartChange() // 触发'发起部门改变时'事件
  },
  // ========== 发起部门改变时 ==========
  launchDepartChange (e) {
    // 获取部门相关信息
    const arr = this.data.listData.depart
    const val = e ? this.data.param.launchDepart : $app.userInfo.departid
    const b =  $app.$common.arrFindEl(arr, val, 'id')
    // 相关数据初始化
    let approveProcess_person = this.data.approveProcess_person
    for (let k in approveProcess_person) { approveProcess_person[k] = [] }
    this.setData({
      ['param.assetsNum']: null, // 清空'资产编号'
      ['param.isAssetsAgree']: 0, // 默认不经过(经资产管理部审批)
      ['param.launchDepartName']: b ? b.departname : null, // 赋值'launchDepartName'
      judge_isAssetsAgree: !Boolean(b && b.level === '2'), // 判断'经资产管理部审批'是否可用
      approveProcess_person // 初始化'审批流程具体人员'
    })
    this.getApproveProcessPerson(val) // 获取审批流程的具体人员
    this.getListData_assetsNum(val) // 获取列表数据: 资产编号
    this.assetsNumChange() // 触发'资产编号改变时'事件
  },
  // ========== 获取审批流程的具体人员 ==========
  getApproveProcessPerson (departId) {
    if (!$app.$common.noNull(departId)) return
    $app.$api.agree.getAgreeDepartMessage({
      id: $app.userInfo.id,
      name: $app.userInfo.name,
      departid: departId
    }).then(({ data, code, message }) => {
      console.log('api-审批流程的具体人员', data)
      if (code === 2) {
        this.setData({ approveProcess_warning: message })
        $app.$common.message(message, 'warning') // 提示信息
        return
      }
      let newData = data || []
      let approveProcess_person = this.data.approveProcess_person
      newData.forEach(b => {
        const k = b.id
        const arr = b.name ? b.name.split(',') : []
        approveProcess_person[k] = arr
      })
      this.setData({
        approveProcess_warning: null,
        approveProcess_person
      })
    }).catch((res, type) => {})
  },
  // ========== 获取列表数据: 资产编号 ==========
  getListData_assetsNum (departId) {
    if (!$app.$common.noNull(departId)) return
    // == 资产编号树形图 ===
    // $app.$common.openLoading() // 开启加载
    // $app.$api.agree.getAssetsTree({}).then(({data}) => {
    //   this.setData({ ['listData.assetsNum']: data })
    //   console.log('api-列表数据: 资产编号树形图', data)
    //   $app.$common.closeLoading() // 关闭加载
    // }).catch(() => {})
    // == 资产编号 ===
    $app.$common.openLoading() // 开启加载
    $app.$api.agree.getAssetsNumByDepart({
      departId: departId,
      roledept: $app.userInfo.roledept
    }).then(({data}) => {
      console.log('api-列表数据: 资产编号', data)
      let newData = $app.$common.assetsNumSort(data || [])
      this.setData({ ['listData.assetsNum']: newData })
      $app.$common.closeLoading() // 关闭加载
    }).catch(() => {})
  },
  // ========== 资产编号改变时 ==========
  assetsNumChange (e) {
    if (!this.data.param.assetsNum) return
    let param = this.data.param
    let assetsNumArr = param.assetsNum.split(',')
    const info = {
      // manageCompany: 'departid',
      manageCompanyName: 'departName',
      assetsType: 'assetsType',
      locatePlace: 'assetsAddress',
      useCondition: 'useSituation'
    }
    param.manageCompanyArr = []
    for (const k in info) {
      param[k + 'Arr'] = []
      param[k + 'item'] = ''
      param[k + 'site'] = []
    }
    assetsNumArr && assetsNumArr.forEach(b => {
      this.data.listData.assetsNum.forEach(b1 => {
        if (b1.assetsNum === b) {
          for (const k in info) {
            if (k === 'useCondition' || k === 'assetsType') {
              // console.log(this.data.listData.useSituation, '$app.listData.useSituation')
              let item = $app.$common.arrFindEl($app.listData[info[k]], b1[info[k]], 'id', 'name')
              param[k + 'site'].push(item)
              param[k + 'Arr'].push(b1[info[k]])
            } else {
              param[k + 'Arr'].push(b1[info[k]])
            }
          }
          let departId = b1.departid || b1.departId || null
          param.manageCompanyArr.push(departId)
        }
      })
    })
    for (const k in info) {
      if (k === 'useCondition' || k === 'assetsType') {
        param[k + 'item'] = param[k + 'site'].join(',')
      } else {
        param[k] = param[k + 'Arr'].join(',')
      }
    }
    this.setData({ param })
    // 获取资产编号相关信息
    // const b = e ? e.detail.currentTarget.dataset.item : null
    // let param = this.data.param
    // const info = {
    //   // manageCompany: 'departid',
    //   manageCompanyName: 'departName',
    //   assetsType: 'assetsType',
    //   locatePlace: 'assetsAddress',
    //   useCondition: 'useSituation'
    // }
    // for (const k in info) { param[k] = b ? b[info[k]] : null }
    // param.manageCompany = b ? (b.departid || b.departId || null) : null
    // this.setData({ param })
  },
  // ========== 涉及金额改变时 ==========
  includeMoneyChange (e) {
    // 获取'列表数据: 审批流程'
    const includeMoney = this.data.param.includeMoney
    const approveProcess = $app.listData.approveProcess
    let arr = []
    approveProcess.forEach(b => {
      b.includeMoney && b.includeMoney.includes(includeMoney) && arr.push(b)
    })
    for (const i in approveProcess) {
      let b = approveProcess[i]
      b.show = Boolean(b.includeMoney && b.includeMoney.includes(includeMoney))
    }
    this.setData({ ['listData.approveProcess']: arr })
  },
  // ========== 管理方式改变时 ==========
  manageTypeChange (e) {
    // 获取当前使用的权限对应web页名称(用于判断提交按钮权限)
    const b = e ? e.detail.currentTarget.dataset.item : null
    this.setData({ judgeAuthName: b ? b.Auth : '' })
  },
  // ========== 经过资产管理部改变时 ==========
  isAssetsAgreeChange (e) {
    const isAssetsAgree = this.data.param.isAssetsAgree
    let approveProcess = $app.listData.approveProcess
    let i = $app.$common.arrFindIndex (approveProcess, 'assetsManageDepart', 'id')
    approveProcess[i].show = Boolean(isAssetsAgree)
    this.setData({ ['listData.approveProcess']: approveProcess })
  },
  // ========== 提交申请 ==========
  save (e) {
    let param = this.data.param
    console.log(param, 'param')
    // 1.验证是否有'审批流程的警告提示'
    if (this.data.approveProcess_warning) {
      this.$common.message(this.data.approveProcess_warning, 'warning') // 提示信息
      return
    }
    // 2.验证必填项
    let verify = {
      launchDepartName: '发起部门',
      assetsNum: '资产编号',
      includeMoney: '涉及金额',
      manageType: '管理方式',
      assetsStatus: '资产会办情况',
      filenameArr: '附件'
    }
    for (const k in verify) {
      const val = Array.isArray(param[k]) ? param[k][0] : param[k]
      if (!$app.$common.noNull(val)) {
        this.setData({ error: k })
        $app.$common.message(verify[k] + '不能为空') // 提示信息
        return
      }
    }
    this.setData({ error: null })
    // 3.是否需要提交
    const isSubmit = e.currentTarget.dataset.submit
    isSubmit && this.setData({ ['param.agreeType']: 1 })
    // 4.上传
    $app.$common.openLoading() // 开启加载
    this.selectComponent("#zjFile").upload('agree', 'addWenjian') // 文件上传
  },
  // ========== '上传'结束后 ==========
  uploadEnd (e) {
    e = e.detail
    if (e.result === 'fail' || e.result === 'complete') {
      $app.$common.closeLoading() // 关闭加载
      const text = `上传失败${e.failUp}个`
      $app.$common.message(text, 'error')
    } else {
      // $app.$common.closeLoading() // 关闭加载
      this.saveAgain()
    }
  },
  // ========== 继续保存 ==========
  saveAgain () {
    const param = this.data.param
    param.manageCompany = this.data.param.manageCompanyArr.join(',')
    param.assetsType = this.data.param.assetsTypeArr.join(',')
    param.useCondition = this.data.param.useConditionArr.join(',')
    this.data.fileKeys.forEach(k => { param[k] = param[k + 'Arr'].join(',') })
    // 提交申请
    $app.$common.openLoading() // 开启加载
    $app.$api.agree.addAgreeNew(param).then((res) => {
      console.log('api-保存成功', res)
      $app.$common.closeLoading() // 关闭加载
      $app.$common_wx.back() // 返回上一页
      $app.$common.message('保存成功', 'success')
    }).catch(() => {})
  }
})